﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QInfrastructure.Models;


#nullable disable
public class QInfrastructureCache
{
    private static Lazy<MemoryCache> _QCache = new Lazy<MemoryCache>(() =>
    {
        var options = new MemoryCacheOptions
        {

        };
        return new MemoryCache(options);
    }, true);

    /// <summary>
    /// 缓存填充方法表，当查询缓存没有数据时可以通过方法进行注入数据
    /// </summary>
    public static Dictionary<string, Action> CacheActions { get; set; } = new Dictionary<string, Action>();


    /// <summary>
    /// 获取缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public static List<T> GetQCache<T>(string key)
    {
        if (!_QCache.Value.TryGetValue(key, out T value))
        {
            if (CacheActions.ContainsKey(key))
            {
                CacheActions[key]?.Invoke();
            }
            else
            {
                throw new Exception("请先在方法中注册缓存【InitAppSetting.InitQCacheService】");
            }
        }
        return _QCache.Value.Get<List<T>>(key);
    }
    public static List<T> GetQCache<T>()
    {
        var key = typeof(T).FullName;
        if (!_QCache.Value.TryGetValue(key, out List<T> value)||value.Count<=0)
        {
            if (CacheActions.ContainsKey(key))
            {
                CacheActions[key]?.Invoke();
            }
            else
            {
                throw new Exception("请先在方法中注册缓存【InitAppSetting.InitQCacheService】");
            }
        }
        return _QCache.Value.Get<List<T>>(key);
    }



    /// <summary>
    /// 删除缓存
    /// </summary>
    /// <param name="key"></param>
    public static void RemoveQCache(string key)
    {
        _QCache.Value.Remove(key);
    }

    /// <summary>
    /// 添加或者更新缓存
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="key"></param>
    /// <param name="info"></param>

    public static void AddOrUpdateQCache<T>(string key, List<T> info)
    {
        _QCache.Value.Set(key, info);
    }



}
